import { defineElement, ref, watcher } from "zipaper"
import "./index.scss"
import { getParentInstance } from "../../tool"
import type ZipaperType from "zipaper/types/Zipaper"

export let UiCheckGroup = defineElement({
    template: [{
        name: "div",
        attr: {
            class: "ui-check-group"
        },
        children: [{
            name: "slot",
            attr: {},
            children: []
        }]
    }],
    emits: ["input"],
    props: {
        value: {
            default: []
        }
    },
    data() {
        return {
            name: "CheckGroup",
            childsAction: [],
            newValues: this._props.value
        }
    },
    methods: {
        updateClass() {
            for (let key in this.childsAction) {
                if (this.childsAction[key]) {
                    this.childsAction[key](this.newValues.indexOf(key) > -1)
                }
            }
        },
        updateModel(newValue: string) {
            let index = this.newValues.indexOf(newValue)
            if (index > -1) {
                this.newValues.splice(index, 1)
            } else {
                this.newValues.push(newValue)
            }

            this.updateClass()
            this.$emit("input", this.newValues)
        }
    },
    created() {
        watcher(this._props, "value", () => {
            this.newValues = this._props.value
            this.updateClass()
        })
        setTimeout(() => {
            this.updateClass()
        })
    }
})

export let UiCheck = defineElement({
    template: [{
        name: "div",
        attr: {
            "z-bind:class": "'ui-check '+(isChecked?'checked':'unchecked')",
            "z-on:click": function () {
                this.parentInstance?.updateModel(this._props.value)
            }
        },
        children: [{
            name: "span",
            attr: {
                class: "ui-check-icon"
            },
            children: []
        }, {
            name: "slot",
            attr: {},
            children: []
        }]
    }],
    props: {
        value: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            isChecked: ref(false),
            parentInstance: null
        }
    },
    created() {
        getParentInstance.call(this, "CheckGroup", (instance: ZipaperType) => {
            this.parentInstance = instance
            instance.childsAction[this._props.value] = (_isChecked: boolean) => {
                this.isChecked = _isChecked
            }
        })
    },
    beforeDestroy() {
        delete this.parentInstance?.childsAction[this._props.value]
    }
})